package com.chance.cc.crawler.development.scripts.dunkhome;

import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Json;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/2/22 16:33
 * @Description
 *      get文章
 **/
public class DunkhomeCrawlerScript extends CrawlerCommonScript {

    private Logger log = LoggerFactory.getLogger(DunkhomeCrawlerScript.class);
    private static final String REQUEST_AGAIN_TAG = "getArticle_request_again";

    //关键词查询
    private static final String ENTRANCE_KEYWORD_URL = "http://www.dunkhome.com/related_search";
    private static final String NEWS_SEARCH_URL = "http://www.dunkhome.com/news/search\\S*";
    private static final String ITEM_PREFIX = "http://www.dunkhome.com";
    private static final String NEWS_ITEM_URL = "http://www.dunkhome.com/news/\\d+";
    private static final String EVALUATINOS_SEARCH_URL = "http://www.dunkhome.com/evaluations/search\\S*";
    private static final String EVALUATIONS_ITEM_URL = "http://www.dunkhome.com/evaluations/\\d+";
    private static final String COMMENT_ENTRANCE_URL = "http://www.dunkhome.com/[a-z]*/\\d+#comment";
    private static final String COMMENT_URL = "http://www.dunkhome.com/[a-z]*/\\d+\\?page=\\S*";

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return "dunkhome";
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(ENTRANCE_KEYWORD_URL);
        addUrlRegular(NEWS_SEARCH_URL);
        addUrlRegular(NEWS_ITEM_URL);
        addUrlRegular(EVALUATINOS_SEARCH_URL);
        addUrlRegular(EVALUATIONS_ITEM_URL);
        addUrlRegular(COMMENT_ENTRANCE_URL);
        addUrlRegular(COMMENT_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        List<CrawlerRecord> crawlerRecords = new ArrayList<>();

        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            String url = supportSourceRecord.getHttpRequest().getUrl();
            if (url.contains("keys")) {
                initKeyword(requestRecord, supportSourceRecord, crawlerRecords);
            }
        }

        return crawlerRecords;
    }

    /**
     * 解析链接方法
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();

        if (!httpPage.isDownloadSuccess()) {
            log.error("dunkhome page download error!will retry");
            requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        String requestUrl = httpPage.getRequest().getUrl();
        if(requestUrl.matches(NEWS_SEARCH_URL) || requestUrl.matches(EVALUATINOS_SEARCH_URL)){
            searchUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }else if(requestUrl.matches(EVALUATIONS_ITEM_URL)){
            itemUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }else if(requestUrl.matches(COMMENT_URL) || requestUrl.matches(COMMENT_ENTRANCE_URL)){
            commentUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        return parsedLinks;
    }

    private void searchUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks){
        String keyword = (String) httpPage.getRequest().getExtras().get("keyword");
        String requestUrl = httpPage.getRequest().getUrl();
        if(!requestUrl.contains("page")){
            List<Selectable> nodes = httpPage.getHtml().xpath("//ul/li|//div[@class=\"c-items item-eva\"]/div").nodes();
            if(nodes != null && nodes.size() < 1){
                log.error(keyword + " search result is 0!");
                return;
            }
        }
        //翻页
        String nextUrl = "";
        String separated_id = httpPage.getHtml().xpath("//ul/li[last()]/@data-id|//div[@class=\"c-items item-eva\"]/div[last()]/@data-id").get();
        if(StringUtils.isNotBlank(separated_id)){
            nextUrl = requestUrl.split("\\?")[0] + "?";
            if(requestUrl.contains("page=")){
                List<NameValuePair> parse = URLEncodedUtils.parse(requestUrl.split("\\?")[1], Charset.defaultCharset());
                for (NameValuePair nameValuePair : parse) {
                    if("page".equals(nameValuePair.getName())){
                        nextUrl = nextUrl + nameValuePair.getName() + "=" + (Integer.parseInt(nameValuePair.getValue()) + 1) + "&";
                    }else{
                        nextUrl = nextUrl + nameValuePair.getName() + "=" + nameValuePair.getValue() + "&";
                    }
                }
                nextUrl = nextUrl.substring(0,nextUrl.length() - 1);
            }else{
                nextUrl = requestUrl.replace("search","search_load_more") + "&page=2&separated_id=" + separated_id + "&k=";
            }
        }

        if(StringUtils.isNotBlank(nextUrl)){
            CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(nextUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            turnRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
            parsedLinks.add(turnRecord);
        }

        //列表解析
        List<Selectable> nodes = httpPage.getHtml().xpath("//ul/li|//div[@class=\"c-items item-eva\"]/div").nodes();
        for (Selectable node : nodes) {
            String itemUrl = node.xpath("./a[@target=\"_blank\"]/@href|./div[@class=\"item-content\"]/a/@href").get();
            if(StringUtils.isBlank(itemUrl)){
                continue;
            }else{
                itemUrl = ITEM_PREFIX + itemUrl;
            }

            String releaseTime = node.xpath(".//dd[@class=\"news-property\"]/text()|.//span[@class=\"item-time\"]/text()").get();
            if(StringUtils.isBlank(releaseTime)){
                continue;
            }

            try {
                long releaseTimeToLong = DateUtils.parseDate(releaseTime, "yyyy年MM月dd日 HH:mm:ss","yyyy-MM-dd HH:mm").getTime();
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(itemUrl)
                        .recordKey(itemUrl + keyword)
                        .releaseTime(releaseTimeToLong)
                        .copyResultTags()
                        .copyBizTags()
                        .build();
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks){
        String requestUrl = httpPage.getRequest().getUrl();
        CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if(resultTags.hasDataType(comment)){
            CrawlerRequestRecord commentFilter = resultTags.getCategoryTag().getKVTagObjVal("comment_filter_record", CrawlerRequestRecord.class);
            if(commentFilter == null){
                log.error("comment filter can not null !");
                return;
            }

            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(requestUrl+"#comment")
                    .releaseTime(System.currentTimeMillis())
                    .notFilterRecord()
                    .copyBizTags()
                    .needWashed(true)
                    .resultLabelTag(comment)
                    .build();
            commentRecord.setFilter(commentFilter.getFilter());
            commentRecord.setFilterInfos(commentFilter.getFilterInfos());
            resultTags.getCategoryTag().removeLabelTag("comment");
            parsedLinks.add(commentRecord);
        }
    }

    private void commentUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks){
        String nextUrl = httpPage.getHtml().xpath("//a[text()='下一页']/@href").get();
        if(StringUtils.isNotBlank(nextUrl)){
            nextUrl = ITEM_PREFIX + nextUrl;
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(nextUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .needWashed(true)
                    .copyResultTags()
                    .build();
            parsedLinks.add(commentRecord);
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        String requestUrl = page.getRequest().getUrl();

        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(interaction)) {
            if(requestUrl.matches(NEWS_ITEM_URL)){
                crawlerDataList.add(washNewsInteraction(crawlerRecord, page));
            }else if(requestUrl.matches(EVALUATIONS_ITEM_URL)){
                crawlerDataList.add(washEvaluationsInteraction(crawlerRecord,page));
            }
        }

        if (crawlerResultTags.hasDataType(comment)) {
            crawlerDataList.addAll(washComment(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);

        String title = httpPage.getHtml().xpath("//h3/text()").get();
        String author = httpPage.getHtml().xpath("//span[@class=\"s-name\"]/text()|//span[@class=\"i-nickname\"]/text()").get();
        String releaseTime = httpPage.getHtml().xpath("//div[@class=\"fl\"]/span/text()|//span[@class=\"i-time\"]/text()").get();
        List<String> all = httpPage.getHtml().xpath("//div[@class=\"content s-news-content\"]//text()|//div[@class=\"show-content\"]/p//text()").all();
        StringBuffer conents = new StringBuffer();
        for (String articleText : all) {
            if(StringUtils.isBlank(articleText) || (StringUtils.isNotBlank(articleText) && "APP下载".equals(articleText) || "【get】".equals(articleText) || articleText.contains("扫一扫就可以体验！"))){
                continue;
            }
            conents.append(articleText).append(" ");
        }

        CrawlerData crawlerData = null;
        try {
            Long releaseTimeToLong = StringUtils.isNotEmpty(releaseTime) ? DateUtils.parseDate(releaseTime, "yyyy年MM月dd日 HH:mm:ss","yyyy-MM-dd HH:mm:ss").getTime() : crawlerRequestRecord.getReleaseTime();
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                    .url(itemUrl)
                    .releaseTime(releaseTimeToLong)
                    .addContentKV(Field_Content, conents.toString())
                    .addContentKV(Field_Title, title)
                    .addContentKV(Field_Author, author)
                    .build();
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return crawlerData;
    }

    public CrawlerData washNewsInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);

        String views = httpPage.getHtml().xpath("//span[@class=\"view-count\"]/text()").get();
        views = StringUtils.isNotBlank(views) ? views : "0";
        String comments = httpPage.getHtml().xpath("//span[@class=\"s-count\"]/text()").get();
        comments = StringUtils.isNotBlank(comments) ? comments : "0";
        String releaseTime = httpPage.getHtml().xpath("//div[@class=\"fl\"]/span/text()").get();

        try {
            Long releaseTimeToLong = StringUtils.isNotEmpty(releaseTime) ? DateUtils.parseDate(releaseTime, "yyyy年MM月dd日 HH:mm:ss").getTime() : crawlerRequestRecord.getReleaseTime();
            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), interaction.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                    .releaseTime(releaseTimeToLong)
                    .url(itemUrl)
                    .addContentKV(Field_I_Comments, comments)
                    .addContentKV(Field_I_Views,views)
                    .build();

            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return null;

    }

    public CrawlerData washEvaluationsInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);

        String likes = httpPage.getHtml().xpath("//span[@class=\"item-like\"]/text()").get();
        likes = StringUtils.isNotBlank(likes) ? likes : "0";
        String comments = httpPage.getHtml().xpath("//span[@class=\"item-comment\"]/text()").get();
        comments = StringUtils.isNotBlank(comments) ? comments : "0";
        String releaseTime = httpPage.getHtml().xpath("//span[@class=\"i-time\"]/text()").get();

        try {
            Long releaseTimeToLong = StringUtils.isNotEmpty(releaseTime) ? DateUtils.parseDate(releaseTime, "yyyy-MM-dd HH:mm:ss").getTime() : crawlerRequestRecord.getReleaseTime();
            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), interaction.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                    .releaseTime(releaseTimeToLong)
                    .url(itemUrl)
                    .addContentKV(Field_I_Comments, comments)
                    .addContentKV(Field_I_Likes,likes)
                    .build();

            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return null;

    }

    public List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        String requestUrl = httpPage.getRequest().getUrl();
        String articleKey = "";
        if(requestUrl.matches(COMMENT_ENTRANCE_URL)){
            articleKey = requestUrl.substring(requestUrl.lastIndexOf("/") + 1,requestUrl.lastIndexOf("#"));
        }else if(requestUrl.matches(COMMENT_URL)){
            articleKey = requestUrl.substring(requestUrl.lastIndexOf("/") + 1,requestUrl.lastIndexOf("?"));
        }

        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"comment-list\"]/ul/li").nodes();
        for (Selectable node : nodes) {
            String author = node.xpath(".//div[@class=\"c-nickname\"]/span/text()").get();
            String content = node.xpath(".//div[@class=\"c-message\"]/p").get();
            String releaseTime = node.xpath(".//div[@class=\"c-nickname\"]/text()").get();

            String commentId = node.xpath("./@data-id").get();
            CrawlerData crawlerData = null;
            try {
                crawlerData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), comment.enumVal(), commentId))
                        .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                        .releaseTime(DateUtils.parseDate(releaseTime.trim(),"  yyyy-MM-dd HH:mm:ss").getTime())
                        .url(requestUrl)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .addContentKV(Field_Author, author)
                        .addContentKV(Field_Content, content)
                        .build();
                crawlerDataList.add(crawlerData);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return crawlerDataList;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 5) {
                log.error("dunkhome download page the number of retries exceeds the limit" +
                        ",request url {}", crawlerRecord.getHttpRequest().getUrl());
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        CrawlerRequestRecord crawlerRequestRecord = null;
        if(type == null){
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }else{
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        if (crawlerRequestRecord == null) {
            return;
        }

        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private void initKeyword(CrawlerRequestRecord requestRecord, CrawlerRequestRecord supportSourceRecord, List<CrawlerRecord> crawlerRecords) {
        HttpPage internalDownloadPage = supportSourceRecord.getInternalDownloadPage();
        String sourceUrl = (String ) requestRecord.getHttpRequest().getExtras().get("searchKwSourceUrl");
        if(StringUtils.isEmpty(sourceUrl)){
            log.error("sourceUrl can not null !");
            return;
        }
        Json json = internalDownloadPage.getJson();
        String msg = json.jsonPath($_type + ".msg").get();
        if (!"success".equals(msg)) {
            log.error("keyword page [{}] download error!", internalDownloadPage.getRequest().getUrl());
            return;
        }

        List<String> all = json.jsonPath($_type + ".content").all();
        for (String data : all) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String keyword = jsonObject.getString("keyword");

            String itemUrl = null;
            try {
                itemUrl = String.format(sourceUrl, URLEncoder.encode(keyword, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(requestRecord)
                    .httpUrl(itemUrl)
                    .releaseTime(System.currentTimeMillis())
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            turnRecord.tagsCreator().bizTags().addKeywords(keyword);
            turnRecord.getHttpRequest().addExtra("keyword",keyword);
            crawlerRecords.add(turnRecord);
        }
    }

    private static String getString(String regx, String input) {
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }
}
